package com.example.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "SessionServlet", value = "/SessionServlet")
public class SessionServlet extends BaseServlet {
    //    创建Session
    protected void createOrGetSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        创建和获取Session对象
        HttpSession session = request.getSession();
//        判断是否为新创建出来的
        boolean isNew = session.isNew();
//        获取Session会话的唯一标识id
        String id = session.getId();
        response.getWriter().write("得到的Session的id为" + id + "<br>");
        response.getWriter().write("得到的Session是否为新创建的" + isNew);
    }

    //    设置Session域中数据
    protected void setAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().setAttribute("key1", "value1");
        response.getWriter().write("Session域中的key1的数据设置为value1");
    }

    //    获取Session域中数据
    protected void getAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object key1 = request.getSession().getAttribute("key1");
        response.getWriter().write("获得Session域中的key1的数据为" + key1);
    }

    //    获取默认生命周期 30min 在tomcat内默认配置
    protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        获取session默认超时时长
        int maxInactiveInterval = request.getSession().getMaxInactiveInterval();
        response.getWriter().write("Session的默认超时时长为" + maxInactiveInterval);
    }

    //    设置生命周期 3s
    protected void life3(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//    获取Session对象
        HttpSession session = request.getSession();
//        设置当前Session3s后
        session.setMaxInactiveInterval(3);
        response.getWriter().write("Session的生命周期已设置为3s");
    }

    //    设置生命周期立即销毁
    protected void die(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//    获取Session对象
        HttpSession session = request.getSession();
//        设置当前Session立即超时
//        session.setMaxInactiveInterval(0);
        session.invalidate();
        response.getWriter().write("Session的生命周期立即销毁");
    }

}